import { _decorator, Component, Node, Vec3, instantiate } from "cc";
import { ResMgr } from "../Managers/ResMgr";
import MapNavAgent from "../AStar/MapNavAgent";
import { EventMgr } from "../Managers/EventMgr";
import { EnemyCtrl } from "./EnemyCtrl";
const { ccclass, property } = _decorator;

import { EnmeyState } from "./EnemyCtrl";

@ccclass("EnmeyMgr")
export class EnmeyMgr extends Component {
    public static Instance: EnmeyMgr = null;

    private ulevel: number = 0;
    private roadSet: Array<any> = null;

    private genNum: number = 0;
    private genCount: number = 5;
    private root: Node = null;


    onLoad(): void {
        if (EnmeyMgr.Instance === null) {
            EnmeyMgr.Instance = this;
        }
        else {
            this.destroy();
            return;
        }

        EventMgr.Instance.add_event_listenner("PlayerDead", this, this.onPlayerDead);
    }

    onPlayerDead(): void { // 停止产生敌人;
        this.unscheduleAllCallbacks();
    }

    loadLevelData(level: number, roadEditor: Node): void { // 加载关卡的数据;
        this.ulevel = level;
        this.roadSet = [];

        // -4, -3, -2, -1, 0, 1, 2, 3, 4 --->共九条路径
        for(var j = -4; j <= 4; j ++) {
            // 一条路径点;
            var roadData = [];
            for(var i = 0; i < roadEditor.children.length; i ++) {
                var pos = roadEditor.children[i].getWorldPosition();
                pos.x = j;
                roadData.push(pos);
            }
            this.roadSet.push(roadData);
        }
        
    }

    genEnemiesOneTime(): void {
        for(var i = 0; i < this.roadSet.length; i ++) {
            var enemy_prefab = ResMgr.Instance.getAsset("charctors/enemy");
            var enemy = instantiate(enemy_prefab);
            this.root.addChild(enemy);
            var speed: number = 2 + Math.random() * 3; // 表格数据来对接;
            var roadData = this.roadSet[i];
            var killValue: number = 10;

            var ctrl: EnemyCtrl = enemy.addComponent(EnemyCtrl); // 确保 onLoad被调用;
            ctrl.initEnemyConfig({hp: 10, speed: speed, roadData: roadData, killValue: killValue}); // 从Excel表格数据来对接;
            ctrl.setState(EnmeyState.Run);
        }
        
        
    }

    genEnmeies(root: Node): void {
        this.root = root;

        this.genEnemiesOneTime();   
        
        this.genNum ++;
        EventMgr.Instance.dispatch_event("UIEvent_GenEnmey", {genNum: this.genNum, desic: "第" + this.genNum + "波已产生"});

        if (this.genNum < this.genCount) {
            var time = 3 + Math.random() * 2;
            this.scheduleOnce(function() {
                this.genEnmeies(this.root);
            }.bind(this), time);
        }
        else { // 本轮敌人产生完了
            EventMgr.Instance.dispatch_event("GenEnemyEnd", null);
        }

    }
}
